#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
界面元素解析器
负责解析和提取网页界面中的关键元素
"""

import logging
from typing import Dict, List, Any, Optional, Tuple

logger = logging.getLogger(__name__)

class InterfaceParser:
    """
    界面解析器，负责从网页DOM中提取有效信息
    """
    
    def __init__(self):
        """初始化界面解析器"""
        self.browser = None  # 实际项目中需要传入浏览器控制实例
    
    def set_browser(self, browser):
        """设置浏览器实例"""
        self.browser = browser
    
    def extract_courses_list(self) -> List[Dict[str, Any]]:
        """
        提取课程列表
        
        Returns:
            List[Dict]: 课程列表，每个课程包含id、name、status等信息
        """
        courses = []
        
        try:
            # 查找课程列表容器
            course_elements = self.browser.find_elements_by_xpath("//div[contains(@class, 'course-item')]")
            
            for index, element in enumerate(course_elements):
                try:
                    # 提取课程信息
                    course_id = element.get_attribute("data-id") or f"course_{index}"
                    course_name = self._get_element_text(element, ".//div[contains(@class, 'course-name')]")
                    teacher_name = self._get_element_text(element, ".//div[contains(@class, 'teacher-name')]")
                    status_text = self._get_element_text(element, ".//div[contains(@class, 'status')]")
                    
                    # 判断课程状态
                    if "已完成" in status_text:
                        status = "completed"
                    elif "待评价" in status_text:
                        status = "pending"
                    else:
                        status = "unknown"
                    
                    # 构建课程信息对象
                    course = {
                        "id": course_id,
                        "name": course_name,
                        "teacher": teacher_name,
                        "status": status,
                        "element_index": index
                    }
                    
                    courses.append(course)
                    
                except Exception as e:
                    logger.error(f"提取第{index}个课程信息失败: {e}")
                    continue
            
            logger.info(f"成功提取{len(courses)}个课程信息")
            return courses
            
        except Exception as e:
            logger.error(f"提取课程列表失败: {e}")
            return []
    
    def extract_question_info(self) -> Dict[str, Any]:
        """
        提取当前问题的信息
        
        Returns:
            Dict: 包含问题ID、类型、文本等信息
        """
        try:
            # 尝试获取问题容器
            question_container = self.browser.find_element_by_xpath("//div[contains(@class, 'question-container')]")
            
            # 提取问题ID
            question_id = question_container.get_attribute("data-id") or "unknown_id"
            
            # 提取问题文本
            question_text = self._get_element_text(question_container, ".//div[contains(@class, 'question-text')]")
            
            # 判断问题类型
            has_options = len(self.browser.find_elements_by_xpath("//div[contains(@class, 'option')]")) > 0
            has_textarea = len(self.browser.find_elements_by_xpath("//textarea")) > 0
            
            if has_options:
                question_type = "choice"
            elif has_textarea:
                question_type = "text"
            else:
                question_type = "unknown"
            
            # 获取选项信息（如果是选择题）
            options = []
            if question_type == "choice":
                option_elements = self.browser.find_elements_by_xpath("//div[contains(@class, 'option')]")
                for idx, option_element in enumerate(option_elements):
                    option_id = option_element.get_attribute("data-id") or f"option_{idx}"
                    option_text = option_element.text.strip()
                    options.append({
                        "id": option_id,
                        "text": option_text,
                        "index": idx
                    })
            
            # 构建问题信息
            question_info = {
                "id": question_id,
                "type": question_type,
                "text": question_text,
                "options": options if question_type == "choice" else []
            }
            
            logger.info(f"成功提取问题信息: {question_id}, 类型: {question_type}")
            return question_info
            
        except Exception as e:
            logger.error(f"提取问题信息失败: {e}")
            return {
                "id": "unknown",
                "type": "unknown",
                "text": "",
                "options": []
            }
    
    def extract_completion_info(self) -> Dict[str, Any]:
        """
        提取评教完成页面的信息
        
        Returns:
            Dict: 包含完成状态、总分等信息
        """
        try:
            # 尝试获取完成信息容器
            completion_container = self.browser.find_element_by_xpath("//div[contains(@class, 'completion-notice')]")
            
            # 提取完成信息文本
            completion_text = completion_container.text.strip()
            
            # 提取总分信息（如果有）
            score_element = self.browser.find_element_by_xpath("//div[contains(@class, 'score')]")
            score_text = score_element.text.strip() if score_element else ""
            
            # 提取评分（如果有）
            score = None
            import re
            score_match = re.search(r'(\d+(\.\d+)?)', score_text)
            if score_match:
                score = float(score_match.group(1))
            
            # 构建完成信息
            completion_info = {
                "status": "completed",
                "message": completion_text,
                "score": score,
                "timestamp": self._get_timestamp()
            }
            
            logger.info(f"成功提取评教完成信息: 分数={score}")
            return completion_info
            
        except Exception as e:
            logger.error(f"提取完成信息失败: {e}")
            return {
                "status": "unknown",
                "message": "",
                "score": None,
                "timestamp": self._get_timestamp()
            }
    
    def extract_error_info(self) -> Dict[str, Any]:
        """
        提取错误页面信息
        
        Returns:
            Dict: 包含错误类型、消息等信息
        """
        try:
            # 尝试获取错误信息容器
            error_container = self.browser.find_element_by_xpath("//div[contains(@class, 'error-message')]")
            
            # 提取错误信息文本
            error_text = error_container.text.strip()
            
            # 判断错误类型
            error_type = "unknown"
            if "登录" in error_text or "身份验证" in error_text:
                error_type = "authentication"
            elif "网络" in error_text or "连接" in error_text:
                error_type = "network"
            elif "超时" in error_text or "timeout" in error_text.lower():
                error_type = "timeout"
            elif "权限" in error_text or "permission" in error_text.lower():
                error_type = "permission"
            
            # 构建错误信息
            error_info = {
                "type": error_type,
                "message": error_text,
                "timestamp": self._get_timestamp()
            }
            
            logger.warning(f"检测到错误: {error_type} - {error_text}")
            return error_info
            
        except Exception as e:
            logger.error(f"提取错误信息失败: {e}")
            return {
                "type": "unknown",
                "message": "无法识别的错误",
                "timestamp": self._get_timestamp()
            }
    
    def _get_element_text(self, parent_element, xpath: str) -> str:
        """
        获取指定元素的文本内容
        
        Args:
            parent_element: 父元素
            xpath: 相对于父元素的XPath
            
        Returns:
            str: 元素文本
        """
        try:
            element = parent_element.find_element_by_xpath(xpath)
            return element.text.strip()
        except Exception:
            return ""
    
    def _get_timestamp(self) -> str:
        """
        获取当前时间戳
        
        Returns:
            str: 格式化的时间戳
        """
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S") 